滑鼠移動元素觸發事件練習
<body>
<div class="box"></div>
</body>
var el = document.querySelector('.box');
mousemove
,設定好functionel.addEventListener('mousemove',function(e){
alert('已觸碰');
},false);
//Html
<body>
<ul>
<li>screenX: <span class="screenX"></span> screenY: <span class="screenY"></span></li>
<li>pageX: <span class="pageX"></span> pageY: <span class="pageY"></span> </li>
<li>clientX: <span class="clientX"></span> clientY: <span class="clientY"></span></li>
</ul>
</body>
var screenX = document.querySelector('.screenX');
var screenY = document.querySelector('.screenY');
var pageX = document.querySelector('.pageX');
var pageY = document.querySelector('.pageY');
var clientX = document.querySelector('.clientX');
var clientY = document.querySelector('.clientY');
textContent
來對應各自數值function getPosition(e) {
screenX.textContent = e.screenX;
screenY.textContent = e.screenY;
pageX.textContent = e.pageX;
pageY.textContent = e.pageY;
clientX.textContent = e.clientX;
clientY.textContent = e.clientY;
}
var el = document.body;
el.addEventListener('mousemove', getPosition, false);
練習滑鼠指標黏住一顆球,隨著滑鼠移動跟著移動,透過client
X跟Y軸的數字,等同於球的上邊左邊距離邊線的數值
滑鼠指標通常是左上角開始計算
//Html
<body>
<div class="mouseball"></div>
</body>
//Css
.mouseball{
width: 50px;
height: 50px;
position: fixed;
border-radius:50% 50%; background: #000;
}
client
X軸跟Y軸,再來那顆球var clientX = document.querySelector('.clientX');
var clientY = document.querySelector('.clientY');
var mouseBall = document.querySelector('.mouseball');
function getPosition(e) {
clientX.textContent = e.clientX;
clientY.textContent = e.clientY;
mouseBall.style.left =e.clientX+'px';
mouseBall.style.top =e.clientY+'px';
}
var el = document.body;
el.addEventListener('mousemove', getPosition, false);